<template>
  <slot />
</template>
<script lang="ts" setup>
import { RESET_CURRENT_USER, useUserStore, TENANT_ID } from '@/store/user';
import { transferToken } from '@/api/user/login';
import { setExpireTime, setCookie } from '@/utils/common-util';
const ROUTE_PARAM_ACCESS_TOKEN = 'access_token';
const redirectUrl = 'redirect_url';
const { proxy } = getCurrentInstance();

onBeforeMount(() => {
  accessFromConsole();
});

function accessFromConsole() {
  // 清除token
  const userStore = useUserStore();
  userStore[RESET_CURRENT_USER]();
  try {
    // 本地存储租户信息
    if (proxy.$route.query.tenantId) {
      setCookie(TENANT_ID, proxy.$route.query.tenantId);
    }
    const param = proxy.$route.query[ROUTE_PARAM_ACCESS_TOKEN];
    if (param) {
      userStore.SET_TOKEN(param as string);
      transferToken().then((res: any) => {
        if (res.data) {
          userStore.SET_TOKEN(res.data.accessToken, res.data.refreshToken);
          setExpireTime(res.data.expireTime);
          if (proxy.$route.query[redirectUrl]) {
            let redirect = proxy.$route.query[redirectUrl];
            redirect = typeof redirect === 'string' ? redirect : redirect[0];
            proxy.$router.push(decodeURIComponent(redirect));
          } else {
            proxy.$router.push('/');
          }
        }
      });
    } else {
      throw new Error(`缺少参数${ROUTE_PARAM_ACCESS_TOKEN}`);
    }
  } catch (error) {
    console.error(error);
  }
}
</script>
